package com.ruoyi.tasks.service.impl;

import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.wp.WpArticlesStatus;
import com.ruoyi.rabbit.service.RabbitSenderService;
import com.ruoyi.system.domain.WpKey;
import com.ruoyi.system.service.IDictCategoryService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWpKeyService;
import com.ruoyi.tasks.service.TaskService;
import com.ruoyi.wp.domain.WpArticles;
import com.ruoyi.wp.domain.WpKeyCategory;
import com.ruoyi.wp.service.IWpArticlesService;
import com.ruoyi.wp.service.IWpKeyCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    ISysUserService userService;
    @Autowired
    IWpKeyService iWpKeyService;
    @Autowired
    IWpArticlesService iWpArticlesService;
    @Autowired
    RabbitSenderService rabbitSenderService;
    @Autowired
    IWpKeyCategoryService iWpKeyCategoryService;
    @Autowired
    IDictCategoryService iDictCategoryService;
    @Override
    public void taskArticles(Long userId, Long wpKeyId) {
        SysUser sysUser = userService.selectUserById(userId);
        if(sysUser==null){
            System.out.println("用户信息查询失败！定时任务请求参数UserId异常！定时任务停止运行！");
            return;
        }
        WpKey wpKey = iWpKeyService.selectWpKeyById(wpKeyId);
        if(wpKey==null){
            System.out.println("用户网站未查到，请检查用户是否有添加网站！定时任务停止运行！");
            return;
        }

        WpKeyCategory wpKeyCategory = new WpKeyCategory();
        wpKeyCategory.setWpKeyId(wpKeyId);
        wpKeyCategory.setUserId(userId);
        List<WpKeyCategory> wpKeyCategoryList = iWpKeyCategoryService.selectWpKeyCategoryList(wpKeyCategory);

        Long[] wpKeyIds = wpKeyCategoryList.stream().map(WpKeyCategory::getDictCategoryId).toArray(Long[]::new);

        //查询用户文章，是否有未发布的
        WpArticles wpArticles = new WpArticles();
        wpArticles.setUserId(sysUser.getUserId());
        wpArticles.setStatus(WpArticlesStatus.TO_ISSUE.getCode());
        //默认查询这个用户有配置映射分类的前三条
        List<WpArticles>  wpArticlesList = iWpArticlesService.selectByStatus(wpArticles,wpKeyIds);

        if (wpArticlesList==null||wpArticlesList.size()==0){
            System.out.println("该用户暂无任务要运行！文章列表查询参数为空！");
            return;
        }
        System.out.println("数据库参数添加成功，添加文章发送MQ执行中...");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId",sysUser.getUserId());
        jsonObject.put("wpKey",wpKey);
        jsonObject.put("wpArticlesList",wpArticlesList);
        String json = jsonObject.toString();
        System.out.println("定时任务请求sendTimeJobArticles发送参数为==========================");
        System.out.println(json);
        rabbitSenderService.sendTimeJobArticles(json);

    }
}
